import time

import requests
import json
token="80934899-2fcd-4f17-9cda-4cd740784b03"
def getToken():
    global token  # 声明使用全局变量
    url = "https://test-aigateway.hitachi-helc.com:14443/oauth/oauth/token?grant_type=client_credentials&client_id=hsd_aigc_client&client_secret=Hitachi@2024"
    payload={}
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "MyPythonApp/1.0",  # 避免被拦截
    }
    try:
        response = requests.post(url, headers=headers, data=payload)
        response.raise_for_status()  # 如果状态码不是200会抛出HTTPError
        responseDict = response.json()  # 直接使用.json()方法
        token = responseDict["access_token"]
        return token
    except requests.exceptions.RequestException as e:
        print("请求失败:", e)
        print(response.text)
    except json.JSONDecodeError as e:
        print("JSON解析失败:", e)
    except KeyError as e:
        print("响应中没有access_token字段:", e)
    return token  # 返回全局变量token
def getAI(prompt):
    token=getToken()
    url = "https://test-aigc.hitachi-helc.com:14443/v1/open/chat/common"
    payload = json.dumps({
      "tenantId": 33,
      "accountCode": "GZP20240731001",
      "accountType": "zhipu-4.0",
      "temperature": 0.01,
      "modelType": "CHAT_ZHI_PU_40",
      "messages": [
        {
          "role": "user",
          f"content": f"{prompt}",
          "contentType": "text"
        }
      ]
    })
    headers = {
      'Authorization': f'Bearer {token}',
      'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return json.loads(response.text)["message"]
if __name__=="__main__":
    message="全球制冷龙头三花智控杀入港股！一季度爆赚9亿，机器人业务即将起飞？"
    head="有网友发表帖子"
    body="【"+message+"】"
    end="他对股市的态度是看涨，看平，看跌，还是分辨不出来态度？最终必须使用【】将其态度括起来。直接给出结果不要做任何解释！"
    startTime=time.time()
    print(getAI(head+body+end))
    endTime=time.time()
    print(endTime-startTime)
